//
//  IDOLaunchAd.m
//  IDOLaunchAd
//
//  Created by 卓勇  on 2017/6/5.
//  Copyright © 2017年 zhuoyong. All rights reserved.
//

#import "IDOLaunchAd.h"

@interface IDOLaunchAd ()

@property (nonatomic, strong) UIWindow *window;
@property (nonatomic, strong) UIImageView *launchImageView; // 启动图
@property (nonatomic, strong) UIImageView *adImageView;// 广告图
@property (nonatomic, strong) IDOLaunchAdButton *skipButton; // 跳过按钮
@property (nonatomic, strong) NSTimer *timer; // 倒计时

@end

@implementation IDOLaunchAd

- (instancetype)init {
    self = [super init];
    
    if (self) {
        [self commonInit];
    }
    
    return self;
}

- (void)commonInit {
    /// 参数初始化
    self.duration = 5;
    self.adImageViewFrame = self.window.bounds;
    self.openURLString = nil;
    self.adImageNameOrURLString = nil;
    self.launchAdButtonType = Default;
}

- (void)showLaunchAd {
    /// 显示广告图片
    // 添加启动图片到最下面
    [self.window addSubview:self.launchImageView];
    // 添加广告图
    [self.window addSubview:self.adImageView];
    // 添加跳过按钮
    [self.window addSubview:self.skipButton];
    
    // 添加单击手势，用于响应广告点击
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognizerClick:)];
    [self.window addGestureRecognizer:tapGestureRecognizer]; // 广告图非全屏时，需要用self.view才能正确响应广告点击事件
    
    // 设置frame
    [self setupLaunchAdFrame];
    
    // 开启定时器
    [self startTimer];
}

- (void)setupLaunchAdFrame {
    /// view布局subViews
    // 启动图片的frame
    if (self.launchImageView.image) {
        self.launchImageView.frame = self.window.bounds;
    }
    
    // 广告图片的frame
    if (!CGRectIsNull(self.adImageViewFrame)) {
        self.adImageView.frame = self.adImageViewFrame;
    } else {
        self.adImageView.frame = self.window.bounds;
    }
}

#pragma mark - Tap Gesture Recognizer Click
- (void)tapGestureRecognizerClick:(UIGestureRecognizer *)gestureRecognizer {
    /// 广告点击
    
    // 响应广告点击方法
    NSLog(@"广告点击......");
    if (self.launchAdClick) {
        self.launchAdClick(self, self.openURLString);
    }
    
    [self removeWithAnimate];
}

#pragma mark - Skip Button Click
- (void)skipButtonClick:(UIButton *)sender {
    /// 跳过按钮点击
    
    NSLog(@"跳过按钮点击......");
    if (self.launchAdFinish) {
        self.launchAdFinish(self);
    }
    
    [self removeWithAnimate];
}

#pragma mark - timer handler
- (void)timerHandler {
    /// 倒计时处理
    switch (_launchAdButtonType) {
        case Circle: {
            if (_skipButton.circleProgress >= 1.0) {
                
                // 广告显示完毕回调
                NSLog(@"广告显示完毕......");
                if (self.launchAdFinish) {
                    self.launchAdFinish(self);
                }
                
                [self removeWithAnimate];
            }
            
            // 更新倒计时状态
            [_skipButton stateWithLaunchAdButtonType:_launchAdButtonType andDuration:(1 / (self.duration * 100))];
        }
            break;
            
        default: {
            self.duration--;
            
            if (self.duration <= 0) {

                // 广告显示完毕回调
                NSLog(@"广告显示完毕......");
                if (self.launchAdFinish) {
                    self.launchAdFinish(self);
                }
                
                [self removeWithAnimate];
            }
            
            // 更新倒计时状态
            [_skipButton stateWithLaunchAdButtonType:_launchAdButtonType andDuration:self.duration];
        }
            break;
    }
}

#pragma mark - getter method
- (UIWindow *)window {
    if (!_window) {
        UIWindow *window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        window.rootViewController = [[UIViewController alloc] init];
        window.rootViewController.view.backgroundColor = [UIColor clearColor];
        window.rootViewController.view.userInteractionEnabled = NO;
        window.windowLevel = UIWindowLevelStatusBar + 1;
        window.hidden = NO;
        window.alpha = 1;
        _window = window;
    }
    return _window;
}

- (UIImageView *)launchImageView {
    if (!_launchImageView) {
        UIImageView *launchImageView = [[UIImageView alloc] init];
        launchImageView.contentMode = UIViewContentModeScaleToFill;
        launchImageView.userInteractionEnabled = YES;
        launchImageView.clipsToBounds = YES;
        launchImageView.image = [self launchImage];
        _launchImageView = launchImageView;
    }
    return _launchImageView;
}

- (UIImageView *)adImageView {
    if (!_adImageView) {
        UIImageView *adImageView = [[UIImageView alloc] init];
        adImageView.contentMode = UIViewContentModeScaleToFill;
        adImageView.userInteractionEnabled = YES;
        adImageView.clipsToBounds = YES;
        _adImageView = adImageView;
    }
    return _adImageView;
}

- (IDOLaunchAdButton *)skipButton {
    if (!_skipButton) {
        switch (_launchAdButtonType) {
            case Circle: {
                CGFloat skipButtonWidth = 40;
                CGFloat skipButtonHeight = 40;
                CGFloat skipButtonX = self.window.bounds.size.width - skipButtonWidth - 20;
                CGFloat skipButtonY = 40;
                
                IDOLaunchAdButton *skipButton = [[IDOLaunchAdButton alloc] initWithFrame:CGRectMake(skipButtonX, skipButtonY, skipButtonWidth, skipButtonHeight) LaunchAdButtonType:_launchAdButtonType];
                skipButton.userInteractionEnabled = YES;
                [skipButton addTarget:self action:@selector(skipButtonClick:) forControlEvents:UIControlEventTouchUpInside];
                skipButton.titleLabel.font = [UIFont systemFontOfSize:12];
                [skipButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [skipButton setTitle:@"跳过" forState:UIControlStateNormal];
                _skipButton = skipButton;
            }
                break;
            
                
            default: {
                NSString *string = [NSString stringWithFormat:@"%lds 跳过", (long)self.duration];
                CGSize stringSize = [string sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12]}];
                
                CGFloat skipButtonWidth = stringSize.width + 15;
                CGFloat skipButtonHeight = stringSize.height + 10;
                CGFloat skipButtonX = self.window.bounds.size.width - skipButtonWidth - 20;
                CGFloat skipButtonY = 40;
                
                IDOLaunchAdButton *skipButton = [[IDOLaunchAdButton alloc] initWithFrame:CGRectMake(skipButtonX, skipButtonY, skipButtonWidth, skipButtonHeight) LaunchAdButtonType:_launchAdButtonType];
                skipButton.userInteractionEnabled = YES;
                skipButton.layer.masksToBounds = YES;
                skipButton.layer.cornerRadius = 10.f;
                skipButton.backgroundColor = [UIColor blackColor];
                [skipButton addTarget:self action:@selector(skipButtonClick:) forControlEvents:UIControlEventTouchUpInside];
                skipButton.titleLabel.font = [UIFont systemFontOfSize:12];
                [skipButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [skipButton setTitle:string forState:UIControlStateNormal];
                _skipButton = skipButton;
            }
                break;
        }
        
    }
    return _skipButton;
}

#pragma mark - dealloc method
- (void)dealloc {
    [self stopTimer];
}

#pragma mark - other method
- (void)startTimer {
    // 销毁定时器
    [self stopTimer];
    
    switch (_launchAdButtonType) {
        case Circle: {
            // 创建一个定时器
            self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(timerHandler) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
        }
            break;
            
        default: {
            // 创建一个定时器
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerHandler) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
        }
            break;
    }
}

- (void)stopTimer {
    // 销毁定时器
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (UIImage *)launchImage {
    // 获取启动图片
    UIInterfaceOrientation currentInterfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
    
    if (UIInterfaceOrientationLandscapeLeft == currentInterfaceOrientation || UIInterfaceOrientationLandscapeRight == currentInterfaceOrientation) {
        // 横屏
        UIImage *imageL = [self launchImageWithType:@"Landscape"];
        if(imageL) {
            return imageL;
        }
    } else {
        // 其它方向
        UIImage *imageP = [self launchImageWithType:@"Portrait"];
        if(imageP) {
            return imageP;
        }
    }
    
    NSLog(@"获取LaunchImage失败!请检查是否添加启动图,或者规格是否有误.");
    return nil;
}

- (UIImage *)launchImageWithType:(NSString *)type {
    CGSize viewSize = [UIScreen mainScreen].bounds.size;
    NSString *viewOrientation = type;
    NSString *launchImageName = nil;
    NSArray* imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    for (NSDictionary* dict in imagesDict)
    {
        CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
        
        if([viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]])
        {
            if([dict[@"UILaunchImageOrientation"] isEqualToString:@"Landscape"])
            {
                imageSize = CGSizeMake(imageSize.height, imageSize.width);
            }
            if(CGSizeEqualToSize(imageSize, viewSize))
            {
                launchImageName = dict[@"UILaunchImageName"];
                UIImage *image = [UIImage imageNamed:launchImageName];
                return image;
            }
        }
    }
    return nil;
}

- (void)removeWithAnimate {
    // 移除视图
    [self stopTimer];
    
    __weak typeof(self) __weakSelf = self;
    
    [UIView animateWithDuration:0.3 animations:^{
        __weakSelf.window.alpha = 0;
    } completion:^(BOOL finished) {
        [__weakSelf remove];
    }];
}

- (void)remove {
    [self stopTimer];
    [self.window.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    self.window.hidden = YES;
    self.window = nil;
}


@end
